<template>
  <view class="redirect-container">
    <view class="content-box">
      <!-- 店铺标签 -->
      <view class="shop-tag">
        <text class="shop-text">
          {{ shopName || '商家' }}
        </text>
      </view>

      <!-- 买家信息 -->
      <view class="buyer-info">
        <view class="buyer-row">
          <text class="buyer-label">
            买家姓名
          </text>
          <text class="buyer-name">
            {{ maijia || '临时买家' }}
          </text>
        </view>
        <view v-if="phone" class="buyer-row">
          <text class="buyer-label">
            联系电话
          </text>
          <text class="buyer-phone">
            {{ phone }}
          </text>
        </view>
      </view>

      <!-- 金额和时间整合区域 -->
      <view class="amount-box">
        <text class="amount-title">
          {{ isOrderShare ? '本单金额' : '当前赊欠金额' }}
        </text>
        <text class="amount-number">
          ¥{{ formatNumber(amount) }}
        </text>
        <!-- 本条订单分享：显示订单时间 -->
        <template v-if="isOrderShare">
          <view class="time-tag time-tag-normal">
            <text class="time-label">
              订单时间
            </text>
            <text class="time-value" style="font-size: 28rpx;">
              {{ orderTime || '-' }}
            </text>
          </view>
        </template>
        <!-- 全部赊欠分享：显示已赊欠天数 -->
        <template v-else>
          <view class="time-tag" :class="Number(days) > 30 ? 'time-tag-warning' : 'time-tag-normal'">
            <text class="time-label">
              已赊欠
            </text>
            <text class="time-value">
              {{ days }}
            </text>
            <text class="time-unit">
              天
            </text>
          </view>
          <text v-if="Number(days) > 0" class="time-range">
            {{ dateRange }}
          </text>
        </template>
      </view>

      <!-- 提示 -->
      <view class="tips">
        <text class="tips-text">
          请及时核对账单，如有疑问请与商家联系
        </text>
      </view>

      <!-- 按钮 -->
      <button class="action-btn" @tap="handleJump">
        查看详细账单
      </button>

      <!-- 错误提示 -->
      <view v-if="errorMsg" class="error-tip">
        <text>{{ errorMsg }}</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { updateUserInfo } from '@/api/member/index';

// 状态栏高度
const statusBarHeight = ref(0);

const targetAppId = ref('');
const targetPath = ref('');
const shortLink = ref('');
const errorMsg = ref('');

// 买家信息
const maijia = ref('');
const phone = ref('');
const amount = ref('0');
const days = ref('0');
const shopName = ref('');
const dateRange = ref('');
const orderId = ref('');
const orderTime = ref('');
const isOrderShare = ref(false); // 是否是本条订单分享
const is_external = ref('0'); ; // 是否防外传
const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}');
onLoad(async (options: any) => {
  console.log('中转页面接收参数:', options, uni.getStorageSync('userInfo'), phone, userInfo.mobile, is_external);

  const res = await updateUserInfo({
    id: options.maijia_id,
    mobile: options.phone,
    nickname: decodeURIComponent(options.maijia || ''),
  });

  if (res.code === 200 && res.data) {
    console.log('res.data.data:', res.data);
    is_external.value = res.data.is_external;
  }

  // 获取系统信息，计算状态栏高度
  const systemInfo = uni.getSystemInfoSync();
  statusBarHeight.value = systemInfo.statusBarHeight || 0;

  targetAppId.value = options.targetAppId || '';
  targetPath.value = options.targetPath || '';
  shortLink.value = options.shortLink || '';

  // 接收买家详细信息
  maijia.value = decodeURIComponent(options.maijia || '');
  phone.value = options.phone || '';
  amount.value = options.amount || '0';
  days.value = options.days || '0';
  shopName.value = decodeURIComponent(options.shopName || '');
  orderId.value = options.orderId || '';
  orderTime.value = decodeURIComponent(options.orderTime || '');

  // 判断是否是本条订单分享（有 orderId 就是本条订单分享）
  isOrderShare.value = !!orderId.value;

  // 计算参考时间范围（当前日期往前推 days 天）
  if (Number(days.value) > 0) {
    dateRange.value = calcDateRange(Number(days.value));
  }

  if (!targetAppId.value && !shortLink.value) {
    errorMsg.value = '参数错误，无法跳转';
  }
});

// 格式化金额
const formatNumber = (num: string | number) => {
  return Number(num).toLocaleString();
};

// 计算日期范围
const calcDateRange = (dayCount: number) => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - dayCount);
  const format = (d: Date) => {
    const y = d.getFullYear();
    const m = `${d.getMonth() + 1}`.padStart(2, '0');
    const day = `${d.getDate()}`.padStart(2, '0');
    return `${y}-${m}-${day}`;
  };
  return `${format(startDate)} 至 ${format(endDate)}`;
};

const handleJump = () => {
  if (targetAppId.value && targetPath.value) {
    const decodedPath = decodeURIComponent(targetPath.value);
    uni.navigateToMiniProgram({
      appId: targetAppId.value,
      path: decodedPath,
      extraData: {
        phone,
      },
      envVersion: 'trial', // 正式版
      success: () => {
        console.log('跳转小程序成功');
      },
      fail: (err) => {
        uni.showModal({
          title: '跳转失败',
          content: `错误信息：${err.errMsg || '未知错误'}\n\n请确保：\n1. 两个小程序已在微信公众平台关联\n2. 目标小程序已发布正式版\n3. 目标页面路径正确`,
          showCancel: false,
        });
      },
    });
  }
  else {
    uni.showToast({
      title: '参数错误',
      icon: 'none',
    });
  }
};
</script>

<style scoped>
.redirect-container {
  position: relative;
  box-sizing: border-box;
  min-height: 100vh;
  overflow: hidden;
  background: #f5f7fa;
}

/* 自定义导航栏 */
.custom-navbar {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  z-index: 1000;
  background: #fff;
  box-shadow: 0 2rpx 8rpx rgb(0 0 0 / 6%);
}

.navbar-content {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 32rpx;
}

.navbar-left {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 80rpx;
  height: 88rpx;
  cursor: pointer;
}

.navbar-title {
  position: absolute;
  left: 50%;
  font-size: 38rpx;
  font-weight: 700;
  color: #1a1a1a;
  letter-spacing: 2rpx;
  transform: translateX(-50%);
}

.navbar-right {
  width: 80rpx;
}

.content-box {
  position: relative;
  z-index: 1;
  box-sizing: border-box;
  width: 100%;
  padding: 20rpx 32rpx 40rpx;
  margin: 0 auto;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 24rpx rgb(0 0 0 / 8%);
}

/* 票根顶部圆形打孔效果 */
.content-box::before {
  position: absolute;
  top: -8rpx;
  right: 0;
  left: 0;
  z-index: 1;
  height: 16rpx;
  content: '';
  background-image: radial-gradient(circle at 24rpx 8rpx, #f5f7fa 12rpx, #fff 12rpx);
  background-repeat: repeat-x;
  background-size: 48rpx 16rpx;
}

/* 票根底部圆形打孔效果 */
.content-box::after {
  position: absolute;
  right: 0;
  bottom: -8rpx;
  left: 0;
  z-index: 1;
  height: 16rpx;
  content: '';
  background-image: radial-gradient(circle at 24rpx 8rpx, #f5f7fa 12rpx, #fff 12rpx);
  background-repeat: repeat-x;
  background-size: 48rpx 16rpx;
}

/* 店铺标签 */
.shop-tag {
  display: inline-flex;
  align-items: center;
  padding: 12rpx 24rpx;
  margin-bottom: 48rpx;
  background: #fff7e6;
  border-radius: 20rpx;
}

.shop-text {
  font-size: 26rpx;
  font-weight: 600;
  color: #fa8c16;
}

/* 买家信息 */
.buyer-info {
  padding: 32rpx;
  margin-bottom: 40rpx;
  background: #fafafa;
  border-radius: 16rpx;
}

.buyer-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
}

.buyer-row:first-child {
  padding-top: 0;
}

.buyer-row:last-child {
  padding-bottom: 0;
}

.buyer-row:not(:last-child) {
  border-bottom: 1rpx solid rgb(0 0 0 / 6%);
}

.buyer-label {
  font-size: 28rpx;
  font-weight: 500;
  color: #8c8c8c;
}

.buyer-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #1a1a1a;
}

.buyer-phone {
  font-size: 30rpx;
  font-weight: 600;
  color: #1a1a1a;
  letter-spacing: 1rpx;
}

/* 金额和时间整合区域 */
.amount-box {
  position: relative;
  padding: 48rpx 32rpx 40rpx;
  margin-bottom: 40rpx;
  text-align: center;
  background: #fff1f0;
  border: 2rpx solid #ffccc7;
  border-radius: 20rpx;
}

.amount-title {
  display: block;
  margin-bottom: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
  color: #8c8c8c;
}

.amount-number {
  display: block;
  margin-bottom: 24rpx;
  font-size: 80rpx;
  font-weight: 700;
  color: #ff4d4f;
  letter-spacing: 2rpx;
}

.time-tag {
  display: inline-flex;
  align-items: baseline;
  padding: 0;
  margin-bottom: 8rpx;
}

.time-label {
  margin-right: 8rpx;
  font-size: 26rpx;
  font-weight: 500;
  color: #8c8c8c;
}

.time-value {
  margin: 0 4rpx;
  font-size: 36rpx;
  font-weight: 700;
}

.time-tag-normal .time-value {
  color: #52c41a;
}

.time-tag-warning .time-value {
  color: #ff4d4f;
}

.time-unit {
  font-size: 26rpx;
  font-weight: 500;
  color: #8c8c8c;
}

.time-range {
  display: block;
  margin-top: 4rpx;
  font-size: 22rpx;
  font-weight: 400;
  color: #8c8c8c;
}

/* 提示 */
.tips {
  padding: 24rpx;
  margin-bottom: 48rpx;
  background: #e6f7ff;
  border-radius: 12rpx;
}

.tips-text {
  display: block;
  font-size: 24rpx;
  font-weight: 500;
  line-height: 36rpx;
  color: #096dd9;
  text-align: left;
}

/* 按钮 */
.action-btn {
  width: 100%;
  height: 96rpx;
  font-size: 32rpx;
  font-weight: 600;
  line-height: 96rpx;
  color: #fff;
  background: #1890ff;
  border: none;
  border-radius: 48rpx;
  box-shadow: 0 4rpx 12rpx rgb(24 144 255 / 30%);
  transition: all 0.3s ease;
}

.action-btn::after {
  border: none;
}

.action-btn:active {
  background: #096dd9;
  box-shadow: 0 2rpx 8rpx rgb(24 144 255 / 30%);
  transform: translateY(2rpx);
}

/* 错误提示 */
.error-tip {
  padding: 24rpx;
  margin-top: 32rpx;
  text-align: center;
  background: #fff1f0;
  border-left: 4rpx solid #ff4d4f;
  border-radius: 12rpx;
}

.error-tip text {
  font-size: 26rpx;
  font-weight: 500;
  color: #cf1322;
}
</style>
